package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.AssistantLink
import com.promise.jokerdream.response.phone.QueryAssistantXmlResponse
import com.promise.jokerdream.utils.UrlFixer
import org.jsoup.Jsoup

// 乐斗助手解析器
class AssistantXmlParser: BaseXmlParser<QueryAssistantXmlResponse>() {
    
    override fun doParse(xmlString: String): QueryAssistantXmlResponse {
        return try {
            val doc = Jsoup.parse(xmlString)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                val pElements = divElement.select("p")
                
                // 检查是否有至少两个p标签
                if (pElements.size >= 2) {
                    val secondP = pElements[1] // 第二个p标签
                    val links = extractLinksFromElement(secondP)
                    
                    QueryAssistantXmlResponse(
                        actionResult = "",
                        assistantLinks = links
                    )
                } else {
                    QueryAssistantXmlResponse(
                        actionResult = "解析失败",
                        assistantLinks = emptyList()
                    )
                }
            } else {
                QueryAssistantXmlResponse(
                    actionResult = "解析失败",
                    assistantLinks = emptyList()
                )
            }
        } catch (e: Exception) {
            QueryAssistantXmlResponse(
                actionResult = e.message.orEmpty(),
                assistantLinks = emptyList()
            )
        }
    }
    
    /**
     * 从元素中提取所有链接
     * @param element 要提取的元素
     * @return 链接列表
     */
    private fun extractLinksFromElement(element: org.jsoup.nodes.Element): List<AssistantLink> {
        val links = mutableListOf<AssistantLink>()
        
        // 查找所有a标签
        val aElements = element.select("a")
        
        for (aElement in aElements) {
            val text = aElement.text().trim()
            val url = aElement.attr("href")
            
            if (text.isNotEmpty() && url.isNotEmpty()) {
                // 判断是否启用：如果开头为"开启"则为false，反之为true
                val enabled = !text.startsWith("开启")
                // 使用UrlFixer修复链接
                val fixedUrl = UrlFixer.fixUrl(url)
                links.add(AssistantLink(text = text, url = fixedUrl, enabled = enabled))
            }
        }
        
        return links
    }
}